/*
 * MainWindow.java
 *
 * Created on June 18, 2008, 8:36 AM
 */

package levelbuilder;

import java.util.*;

import java.io.*;
import javax.swing.*;
import javax.swing.JFileChooser;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
/**
 *
 * @author  ew562c
 */
public class MainWindow extends javax.swing.JFrame {
   // Viewer lview;
    JFileChooser fc;
    SettingsDialog settings;
    
    /** Creates new form MainWindow */
    public MainWindow() {
        fc = new JFileChooser(".");
        
      //  lview = new Viewer();
        initComponents();
        lview.SetBaseImagePath("./data/operation/images/");
        this.setTitle("WiiOperation-Level Builder");
        settings = new SettingsDialog(this,"./data/operation/images/",lview.GetWallImage(), lview.GetHomeImage(),lview.GetBoneImage(), true);
        
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lview = new Viewer();/*
        lview = new javax.swing.JPanel();
        */
        authorTextEdit = new javax.swing.JTextField();
        descriptionTextEdit = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        titleTextEdit = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        newItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        loadItem = new javax.swing.JMenuItem();
        saveItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        settingsItem = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        helpItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        lview.setBackground(new java.awt.Color(0, 0, 0));
        lview.setMaximumSize(new java.awt.Dimension(640, 480));
        lview.setMinimumSize(new java.awt.Dimension(640, 480));
        lview.setPreferredSize(new java.awt.Dimension(640, 480));
        lview.setRequestFocusEnabled(false);

        javax.swing.GroupLayout lviewLayout = new javax.swing.GroupLayout(lview);
        lview.setLayout(lviewLayout);
        lviewLayout.setHorizontalGroup(
            lviewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 640, Short.MAX_VALUE)
        );
        lviewLayout.setVerticalGroup(
            lviewLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 480, Short.MAX_VALUE)
        );

        descriptionTextEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                descriptionTextEditActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Level Title:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
        jLabel3.setText("Level Description:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Author:");

        jMenu1.setText("File");

        newItem.setText("New");
        newItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newItemActionPerformed(evt);
            }
        });
        jMenu1.add(newItem);
        jMenu1.add(jSeparator1);

        loadItem.setText("Load...");
        loadItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadItemActionPerformed(evt);
            }
        });
        jMenu1.add(loadItem);

        saveItem.setText("Save...");
        saveItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveItemActionPerformed(evt);
            }
        });
        jMenu1.add(saveItem);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Settings");

        settingsItem.setText("Image Settings...");
        settingsItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                settingsItemActionPerformed(evt);
            }
        });
        jMenu2.add(settingsItem);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Help");

        helpItem.setText("Show Help...");
        helpItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                helpItemActionPerformed(evt);
            }
        });
        jMenu3.add(helpItem);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lview, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(authorTextEdit, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(descriptionTextEdit))
                                .addComponent(titleTextEdit, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(titleTextEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(descriptionTextEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(authorTextEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lview, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void descriptionTextEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_descriptionTextEditActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_descriptionTextEditActionPerformed

private void newItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newItemActionPerformed
// TODO add your handling code here:
        lview.ClearAll();
}//GEN-LAST:event_newItemActionPerformed

private void loadItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadItemActionPerformed
// TODO add your handling code here:
        int x, y;
        double rot, zoom;
        Object prop;
        String fname;
        XMLConfiguration config;
        
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
             File selFile = fc.getSelectedFile();
             System.out.println("You chose to open this file: " +
             selFile.getAbsolutePath());
             
            try{ 
                config = new XMLConfiguration(selFile.getAbsolutePath());     
                
                titleTextEdit.setText(config.getString("[@title]"));
                descriptionTextEdit.setText(config.getString("[@description]"));
                authorTextEdit.setText(config.getString("[@author]"));
                
                lview.ClearAll();
                String temp[] = (config.getString("bone[@img_file]")).split("/");
                fname=temp[temp.length-1];
                settings.SetBoneImage(fname);
                x = config.getInt("bone[@x]");
                y = config.getInt("bone[@y]");
                rot = config.getDouble("bone[@rotation]");
                zoom = config.getDouble("bone[@zoom]");

                rot = Math.rint(rot*100.0)/100.0;
                zoom = Math.rint(zoom*100.0)/100.0;
                lview.addBone(settings.GetPath()+"/"+fname,x,y,rot,zoom);

                List boneColls = config.getList("bone.collision[@x]");
                
                settings.ClearBoneCollisions();
                for(int i = 0; i < boneColls.size(); i++)
                {
                    CollisionBox cb = new CollisionBox();
                    
                    cb.x = config.getDouble("bone.collision("+i+")[@x]");
                    cb.y = config.getDouble("bone.collision("+i+")[@y]");
                    cb.w = config.getDouble("bone.collision("+i+")[@w]");
                    cb.h = config.getDouble("bone.collision("+i+")[@h]");  
                    
                    settings.AddBoneCollision(cb);
                }
                
                temp = (config.getString("home[@img_file]")).split("/");
                fname=temp[temp.length-1];
                settings.SetHomeImage(fname);
                
                x = config.getInt("home[@x]");
                y = config.getInt("home[@y]");
                rot = config.getDouble("home[@rotation]");
                zoom = config.getDouble("home[@zoom]");
                
                rot = Math.rint(rot*100.0)/100.0;
                zoom = Math.rint(zoom*100.0)/100.0;
                lview.addHome(settings.GetPath()+"/"+fname,x,y,rot,zoom);  
                
                temp = (config.getString("walls[@img_file]")).split("/");
                fname=temp[temp.length-1];
                settings.SetWallImage(fname);
                List walls = config.getList("walls.wall[@x]");
                
                settings.updateImages();
            
                for(int i = 0; i < walls.size(); i++)
                {
                    x = config.getInt("walls.wall("+i+")[@x]");
                    y = config.getInt("walls.wall("+i+")[@y]");
                    rot = config.getDouble("walls.wall("+i+")[@rotation]");
                    zoom = config.getDouble("walls.wall("+i+")[@zoom]");  
                    
                    rot = Math.rint(rot*100.0)/100.0;
                    zoom = Math.rint(zoom*100.0)/100.0;
                    lview.addWall(settings.GetPath()+"/"+fname, x, y, rot, zoom);
                }
                
            } catch (ConfigurationException configEx) {
                configEx.printStackTrace();
            }
            settings.updateImages();
        }
}//GEN-LAST:event_loadItemActionPerformed

private void saveItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveItemActionPerformed
// TODO add your handling code here:                                    
// TODO add your handling code here:
        //Save Level to XML File
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
             File selFile = fc.getSelectedFile();
             System.out.println("You chose to save this file: " +
             selFile.getAbsolutePath());
             
             try{
                 FileOutputStream out;
                 out = new FileOutputStream(selFile.getAbsolutePath());
                 PrintStream p = new PrintStream(out);
                 p.println("<?xml version=\"1.0\"?>");
                 p.println("<level");
                 p.println("   title='"+titleTextEdit.getText()+"'");
                 p.println("   description='"+descriptionTextEdit.getText()+"'");
                 p.println("   author='"+authorTextEdit.getText()+"'");
                 p.println(">");
                 WallObject nObject;
                 
                 nObject = lview.GetBone();
                 if(nObject != null)
                 {
                    p.println("   <bone");
                    p.println("      img_file='/data/operation/images/"+settings.GetBoneImage()+"'"); 
                    p.println("      x='"+nObject.GetX()+"'");
                    p.println("      y='"+nObject.GetY()+"'");
                    p.println("      rotation='"+nObject.GetRotation()+"'");
                    p.println("      zoom='"+nObject.GetZoom()+"'");
                    p.println("   >");
                    
                    Vector<CollisionBox> boneCollisions;
                    boneCollisions = settings.GetBoneCollisions();
                    
                    if(boneCollisions != null)
                    {
                        for(int j = 0; j < boneCollisions.size(); j++)
                        {
                            CollisionBox cb = boneCollisions.elementAt(j);
                            p.println("      <collision x='"+cb.x+"'");
                            p.println("                 y='"+cb.y+"'");
                            p.println("                 w='"+cb.w+"'");
                            p.println("                 h='"+cb.h+"'");
                            p.println("      />");
                        }
                        
                        if(boneCollisions.size() == 0)
                        {
                            p.println("      <collision x='0'");
                            p.println("                 y='0'");
                            p.println("                 w='"+lview.GetBone().GetWidth()+"'");
                            p.println("                 h='"+lview.GetBone().GetHeight()+"'");
                            p.println("      />");
                        }
                    }
                    else
                    {
                        if(boneCollisions.size() == 0)
                        {
                            p.println("      <collision x='0'");
                            p.println("                 y='0'");
                            p.println("                 w='"+lview.GetBone().GetWidth()+"'");
                            p.println("                 h='"+lview.GetBone().GetHeight()+"'");
                            p.println("      />");
                        }
                    }
                    
                    p.println("   </bone>");
                    
                    
                    
                 }
                 
                 nObject = lview.GetHome();
                 if(nObject != null)
                 {
                    p.println("   <home");
                    p.println("      img_file='/data/operation/images/"+settings.GetHomeImage()+"'"); 
                    p.println("      x='"+nObject.GetX()+"'");
                    p.println("      y='"+nObject.GetY()+"'");
                    p.println("      rotation='"+nObject.GetRotation()+"'");
                    p.println("      zoom='"+nObject.GetZoom()+"'");
                    p.println("   />");
                 }
                 
                    p.println("   <walls");
                    p.println("      img_file='/data/operation/images/"+settings.GetWallImage()+"'");
                    p.println("   >");
                    
                    Vector<CollisionBox> wallCollisions;
                    wallCollisions = settings.GetWallCollisions();
                    
                    if(wallCollisions != null && lview.GetWallCount() > 0)
                    {
                        for(int j = 0; j < wallCollisions.size(); j++)
                        {
                            CollisionBox cb = wallCollisions.elementAt(j);
                            p.println("      <collision x='"+cb.x+"'");
                            p.println("                 y='"+cb.y+"'");
                            p.println("                 w='"+cb.w+"'");
                            p.println("                 h='"+cb.h+"'");
                            p.println("      />");
                        }
                        
                        if(wallCollisions.size() == 0)
                        {
                            p.println("      <collision x='0'");
                            p.println("                 y='0'");
                            p.println("                 w='"+lview.GetWall(0).GetWidth()+"'");
                            p.println("                 h='"+lview.GetWall(0).GetHeight()+"'");
                            p.println("      />");
                        }
                    }
                    else if(lview.GetWallCount() > 0)
                    {
                        if(wallCollisions.size() == 0)
                        {
                            p.println("      <collision x='0'");
                            p.println("                 y='0'");
                            p.println("                 w='"+lview.GetWall(0).GetWidth()+"'");
                            p.println("                 h='"+lview.GetWall(0).GetHeight()+"'");
                            p.println("      />");
                        }
                    }
                    
                 for(int i=0; i < lview.GetWallCount(); i++)
                 {
                     nObject = lview.GetWall(i);
                     p.print("      <wall x='"+nObject.GetX()+"' ");  
                     p.print("y='"+nObject.GetY()+"' ");   
                     p.print("rotation='"+nObject.GetRotation()+"' "); 
                     p.print("zoom='"+nObject.GetZoom()+"' />");   
                     p.println("");
                 }
                 p.println("   </walls>");
                 p.println("</level>");
                 p.close();
             } catch (Exception e)
             {
                 System.err.println("Error writing to file.");
             }
             
            try{ 
                 XMLConfiguration out_file = new XMLConfiguration(selFile.getAbsolutePath());
                // out_file.setRootElementName("levels");
                 
            } catch (ConfigurationException configEx) {
                configEx.printStackTrace();
            }
        }
}//GEN-LAST:event_saveItemActionPerformed

private void settingsItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsItemActionPerformed
// TODO add your handling code here:
        settings.setVisible(true);
        settings.setVisible(false);
        settings.dispose();
        lview.SetBoneImage(settings.GetBoneImage());
        lview.SetHomeImage(settings.GetHomeImage());
        lview.SetWallImage(settings.GetWallImage());
        lview.SetBaseImagePath(settings.GetPath());
        lview.UpdateImages();
}//GEN-LAST:event_settingsItemActionPerformed

private void helpItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_helpItemActionPerformed
// TODO add your handling code here:
         JOptionPane.showMessageDialog(null, 
                 "WiiOperation-LevelBuilder v1.1\n"+
                 "\n  By Beardface\n\n" +
                 "Menu: (Save/Load) Level XML File\n" +
                 "Settings:\n" +
                 "  Image Base Path:\n" +
                 "     You will not need to do this unless you want to change the default image location.\n" +
                 "  Choosing Different Images:\n" +
                 "     Images must be located in the Base Path.  When you go to run your levels, you must\n" +
                 "     also make sure that your image is in /operation/images.\n" +
                 "  Setting Image Collision Boxes:\n" +
                 "     If you want to override the image width and height for collision, you can do so\n" +
                 "     by modifying the collision box by clicking 'Set Collision'. In the GUI drag boxes\n" +
                 "     to your liking and click OK when finished.  (Clicking reset sets it back to the\n"+
                 "     Image Width and Height.\n" +
                 "\n\nControls:" +
                 "\nRight click on drawing pane to bring up the menu.\n" +
                 "   Add Wall - Add wall (No limit)\n" +
                 "   Add Bone - Add the bone (1 per level)\n" +
                 "   Add Home - Add the tray (1 per level)\n" +
                 "              This is the start/stop for the level.\n" +
                 "   Copy/Paste - You can copy and paste Walls to make your life easier.\n" +
                 "   Delete   - Use this to delete selected object\n" +
                 "   Reset    - Use this to reset size/rotation of selected object\n" +
                 "\nMoving objects: Select an object (left click) to drag it around\n" +
                 "Rotating objects: Once an object is selected, Hold CTRL and move the mouse to rotate.\n" +
                 "Scaling objects: Once an object is selected, Hold SHIFT and move the mouse to scale.\n" +
                 "\nMore help:\n" +
                 "    #wiidev");
}//GEN-LAST:event_helpItemActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField authorTextEdit;
    private javax.swing.JTextField descriptionTextEdit;
    private javax.swing.JMenuItem helpItem;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenuItem loadItem;
    private Viewer lview;/*
    private javax.swing.JPanel lview;
    */
    private javax.swing.JMenuItem newItem;
    private javax.swing.JMenuItem saveItem;
    private javax.swing.JMenuItem settingsItem;
    private javax.swing.JTextField titleTextEdit;
    // End of variables declaration//GEN-END:variables
    
}
